home *** CD-ROM | disk | FTP | other *** search
- Path: news.sprintlink.net!datalytics!usenet
- From: Rob Stewart <stew@datalytics.com>
- Newsgroups: comp.lang.c++
- Subject: Re: [HELP!!!] Segmentation Fault!
- Date: Tue, 09 Apr 1996 17:55:13 -0400
- Organization: Datalytics, Inc
- Message-ID: <316ADCC1.629F@datalytics.com>
- References: <4k4gja$mm@nuscc.nus.sg>
- NNTP-Posting-Host: 204.62.224.71
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (WinNT; I)
-
- Virus wrote:
- [snip]
- > I keep getting segmentation fault in my program, and I have tried using the
- > debugger (gdb in unix), but I cannot understand what the debugger is trying
- > to say..[snip]
- >
- > char* SpaceStudentFile::readNextField()
- > {
- > char str[40];
- > int i = 0;
- >
- > // take away starting whitespaces
- > while (str[0] = fgetc(fd)) {
- > if (*str == ' ') continue;
- > if (*str == '\t') continue;
- > if (*str == '\n') continue;
- > if (*str == EOF) return NULL;
- > break;
- > }
- >
- > // read from " to next "
- > if (str[0] == '"') {
- > for (i=0; ((str[i] = fgetc(fd)) != '"'); i++)
- > ;
- > str[i]=0;
- > return str;
- > }
- >
- > // else read until next whitespace
- > for (i=1; ((str[i] = fgetc(fd)) != ' ')
- > && (str[i] != '\n') && (str[i] != '\t'); i++)
- > ;
- > str[i] = 0;
- > return str;
- >
- > }
- >
-
- Your problem lies in this function. You have allocated storage
- on the stack (char str[40]), then return the address of that
- storage. By the time the function returns, the array on the
- stack no longer exists. You need persistent storage.
-
- One scheme calls for readNextField to allocate memory on the
- heap and return the pointer to that memory. This introduces an
- ownership problem though, because readNextField allocates but
- doesn't release memory. readNextField's caller must delete the
- memory it allocated. This is subject to problems; it is not a
- wise approach.
-
- Another scheme calls for allocating storage for readNextField to
- use before calling it, passing a pointer to that storage, and
- letting readNextField populate that storage. With this
- approach, readNextField must validate the pointer and it must
- assume that there is sufficient space. This approach is better
- than the first, but it still leaves room for improvement.
-
- The other scheme calls for a class to manage the storage,
- returning an object of that class from readNextField. That is
- the role of a string class. This approach may be beyond what
- you're ready to do, however.
-
- --
- Robert Stewart | My opinions are usually my own.
- Datalytics, Inc. | stew@datalytics.com
-